#!/bin/sh

# script to generate a petbuild
#set -x

. ./build.conf

CWD=`pwd`

usage() {
	echo "USAGE:	./${0##*/} <URL/of/PACKAGE> <\"DESCRIPTION\"> <DEPENDS> <CATEGORY> <BUILD>"
	echo "eg;	./${0##*/} http://example.com/example_source-1.2.3.tar.gz \
\"a light weight example\" +libsample,+libexample BuildingBlock 2slacko"
	echo "	CATEGORY, DEPENDS and BUILD are optional"
	echo
	echo "	You can add .desktop and pinstall/puninstall files if you wish"
	echo "	to the resulting program directory which you will find in"
	echo "	$CWD"
	echo "CATEGORIES:
	Desktop
	System
	Setup
	Utility
	Filesystem
	Graphic
	Document
	Business
	Personal
	Network
	Internet
	Multimedia
	Fun"
	echo
	echo "Minimal error checking is done. Garbage goes in, garbage comes out!"
	echo
	echo "	This doesn't work in all cases! YMMV"
	exit 0
}

[ "$1" ] || usage
[ "$2" ] || usage
[ "$3" ] && DEPENDS="$3" || DEPENDS=''
[ "$4" ] && CATEGORY="$4"|| CATEGORY=BuildingBlock
[ "$5" ] && BUILD="$5" || BUILD=""

# is it a sourceforge link?
echo "$1" | grep 'sourceforge\.net'| grep -q '\/download$' && SF_URL="$1" || SF_URL=
if [ -n "$SF_URL" ];then # yes
	TGT=`curl  $SF_URL|grep -o 'http*.*'|sed 's/\?.*//'`
	SOURCE="${TGT##*/}"
	SRCURL="${TGT%/*}"
else # no
	SOURCE="${1##*/}"
	SRCURL="${1%/*}"
fi
DESCRIPTION="\"$2\"" 

PROG=${SOURCE%-*}
VERSION=${SOURCE##*-}
VERSION=`echo $VERSION | sed 's%\.tar.*%%'`
COMPRESSION=${SOURCE##*.}

mkdir -p pkgs/"$PROG"

cat > pkgs/$PROG/${PROG}.petbuild << _PET
# $PROG
# Builds from https://github.com/puppylinux-woof-CE/petbuilds
# File auto generated by ./mk_petbuild.sh. Edit as necessary.

. ../../func
. ../../build.conf

URL=$SRCURL
PKG=$PROG
VER=$VERSION
COMP=tar.${COMPRESSION}
DESC=$DESCRIPTION
DEPS=$DEPENDS
CAT=$CATEGORY
DESKTOP=${PROG}.desktop
BUILD=$BUILD
CWD=\$(pwd)
[ -z "\$BUILD" ] && BUILD=\$DEF_BUILD
# comment these 2 below if you use a custom package() function
[ -f "\$DESKTOP" ] || DESKTOP=not
[ -z "\$DEPS" ] && DEPS=not

ARCH=\$(uname -m)
case \$ARCH in # set in build.conf
 *64) 	LIBDIR=\$LIBCONF64 
		FLAGS=\$CF64;;
 arm*)	LIBDIR=\$LIBCONFarm
		FLAGS="-O2" ;;
 i686) 	LIBDIR=\$LIBCONF32 
		FLAGS=\$CF32;;
	*) 	LIBDIR=\$LIBCONF32 
		FLAGS="-O2 -march=\$ARCH -mtune=\$ARCH";;
esac

# main
retrieve \${PKG}-\${VER}.\${COMP}
extract \${PKG}-\${VER}.\${COMP}
build_configure \$PKG \$VER \$LIBDIR "\$FLAGS"
package_std \$PKG \$VER \$ARCH \$DESKTOP "\$DESC" \$DEPS \$CAT
_PET

echo -e "Please check pkgs/$PROG/${PROG}.petbuild for sanity\ndone!"
